﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Infrastructure.Aspect.Extensions;
using System.ServiceModel;

namespace Infrastructure.Services
{
    public class UnityServiceHostFactory : System.ServiceModel.Activation.ServiceHostFactory
    {
        public IUnityContainer ContainerService { get; set; }
        public UnityServiceHostFactory()
        {
            try
            {                
                this.ContainerService = System.Web.HttpContext.Current.Application["ContainerService"] as IUnityContainer;
            }
            catch (Exception ex)
            {
                throw new ApplicationException(@"activate compatibility mode http://msdn.microsoft.com/en-us/library/aa702682.aspx" + ex.Message);
            }
        }
        protected override System.ServiceModel.ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            UnityServiceHost host = null;
            var att = Attribute.GetCustomAttribute(serviceType, typeof(ServiceBehaviorAttribute)) as ServiceBehaviorAttribute;
            if (att != null)
            {
                switch (att.InstanceContextMode)
                {
                    case InstanceContextMode.Single:
                        host = new UnityServiceHost(this.ContainerService.Resolve(serviceType), baseAddresses);
                        break;
                    default:
                        host = new UnityServiceHost(serviceType, baseAddresses);
                        host.Container = this.ContainerService;
                        break;
                }
            }
            else
            {
                host = new UnityServiceHost(serviceType, baseAddresses);
                host.Container = this.ContainerService;
            }
            return host;
        }
    }
}
